<template>
  <div class="login-container">
    <van-nav-bar title="黑马头条 - 登录" fixed />
    <van-form @submit="login">
      <van-field
        type="tel"
        v-model="form.mobile"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="rules.mobile"
      >
      </van-field>
      <van-field
        type="password"
        v-model="form.code"
        label="登录密码"
        placeholder="请输入登录密码"
        required
        :rules="rules.code"
      >
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/userAPI'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '13483301331',
        code: '246810'
      },
      // 表单的校验规则对象
      rules: {
        // 手机号的校验规则
        mobile: [
          { required: true, trigger: 'onBlur' },
          { pattern: /^1\d{10}$/, message: '请填写正确的手机号', trigger: 'onBlur' }
        ],
        // 密码的校验规则
        code: [{ required: true, trigger: 'onBlur' }]
      }
    }
  },
  methods: {
    // 映射 mutations 中的方法
    ...mapMutations(['updateTokenInfo']),

    async login () {
      const { data: res } = await loginAPI(this.form)

      console.log(res)

      if (res.message === 'OK') {
        // 把登录成功的结果，存储到 vuex 中
        this.updateTokenInfo(res.data)

        if (this.$route.query.pre) {
          this.$router.push(this.$route.query.pre)
        } else {
          this.$router.push('/')
        }
      }
    }
  }
}
</script>

<style lang='less' scoped>
.login-container {
  padding-top: 46px;
}
</style>
